<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="序列号" prop="sn">
        <el-input v-model="queryParams.sn" placeholder="请输入序列号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="标签码" prop="label">
        <el-input v-model="queryParams.label" placeholder="请输入标签码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:sn:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:sn:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:sn:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Download" @click="handleImport"
          v-hasPermi="['system:sn:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Search" @click="handleSearch">查询设备关联信息</el-button>
      </el-col>
      <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="snList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序列号" align="center" prop="sn" />
      <el-table-column label="标签码" align="center" prop="label" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sn:edit']">修改</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:sn:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备序列号流水对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formref" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="序列号" prop="sn">
          <el-input v-model.number="form.sn" placeholder="请输入序列号" />
        </el-form-item>
        <el-form-item label="标签码" prop="label">
          <el-input v-model="form.label" placeholder="请输入标签码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查询设备关联信息对话框 -->
    <el-dialog :title="title" v-model="searchOpen" width="500px" append-to-body>
      <el-form :model="queryParamsS" ref="queryFormS" :inline="true" label-width="80px">
        <el-form-item label="序列号" prop="sn">
          <el-input v-model="queryParamsS.sn" placeholder="请输入序列号" clearable size="small"
            @keyup.enter.native="handleQueryS" />
        </el-form-item>
        <el-form-item label="标签码" prop="label">
          <el-input v-model="queryParamsS.label" placeholder="请输入标签码" clearable size="small"
            @keyup.enter.native="handleQueryS" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryS">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-form :model="snInfo" :inline="true" label-width="80px">
        <el-form-item label="网关名称">
          <el-input style="width: 300px" disabled v-model="snInfo.gatewayName" />
        </el-form-item>
        <el-form-item label="网关SN">
          <el-input style="width: 300px" disabled v-model="snInfo.serialNumber" />
        </el-form-item>
        <el-form-item label="网关标签">
          <el-input style="width: 300px" disabled v-model="snInfo.gatewayLabel" />
        </el-form-item>
        <el-form-item label="电站名称">
          <el-input style="width: 300px" disabled v-model="snInfo.stationName" />
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadref" :limit="1" accept=".csv" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon><UploadFilled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入csv格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确定</el-button>
        <el-button @click="upload.open = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script name='Sn' setup lang="ts">
import { listSn, getSn, delSn, addSn, updateSn, snDesc } from '@/api/system/sn/sn';
import { getToken } from '@/utils/auth';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 设备序列号流水表格数据
const snList = ref([])
const snInfo = ref({
  gatewayName: '',
  serialNumber: '',
  gatewayLabel: '',
  stationName: '',
})
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
const searchOpen = ref(false)
// 查询参数
const queryParamsS = ref({
  sn: null,
  label: null,
}
)
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  sn: null,
  label: null,
})
// 用户导入参数
const upload = ref({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/sn/importData',
})
// 表单参数
const form = ref({})
// 表单校验
const rules = ref({})
const formref = ref()
const uploadref = ref()
const queryForm = ref()
const queryFormS = ref()

/** 查询设备序列号流水列表 */
const getList = () => {
  loading.value = true;
  listSn(queryParams.value).then((response) => {
    snList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
getList();

const getInfo = () => {
  snDesc(queryParamsS.value).then((response: any) => {
    snInfo.value = response;
  });
}
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}
// 表单重置
const reset = () => {
  form.value = {
    id: null,
    sn: null,
    label: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  formref.value?.resetFields();
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/** 搜索按钮操作 */
const handleQueryS = () => {
  getInfo();
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryForm.value?.resetFields();
  handleQuery();
}
// 多选框选中数据
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 查询设备关联信息按钮操作 */
const handleSearch = () => {
  searchOpen.value = true;
  title.value = '查询设备关联信息';
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加设备序列号流水';
}
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset();
  const id = row.id || ids.value;
  getSn(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改设备序列号流水';
  });
}
/** 提交按钮 */
const submitForm = () => {
  formref.value.validate((valid: any) => {
    if (valid) {
      if (form.value.id != null) {
        updateSn(form.value).then((response) => {
          proxy?.$modal.msgSuccess(t('licence.use_updateXiugai'));
          open.value = false;
          getList();
        });
      } else {
        addSn(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  const ids: any = row.id || ids.value;
  proxy?.$modal
    .confirm('是否确认删除设备序列号流水编号为"' + ids + '"的数据项？')
    .then(function () {
      return delSn(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    })
    .catch(() => { });
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'biz/sn/export',
    {
      ...queryParams.value,
    },
    `sn_${new Date().getTime()}.xlsx`
  );
}
/** 导入按钮操作 */
const handleImport = () => {
  upload.value.title = '导入设备条码';
  upload.value.open = true;
}
// 文件上传中处理
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  upload.value.isUploading = true;
}
// 文件上传成功处理
const handleFileSuccess = (response: any, file: any, fileList: any) => {
  upload.value.open = false;
  upload.value.isUploading = false;
  uploadref.value.clearFiles();
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', $t('licence.use_daoRujieGuo'), { dangerouslyUseHTMLString: true });
  getList();
}
// 提交上传文件
const submitFileForm = () => {
  uploadref.value.submit();
}

</script>
